package com.azt.front.interceptor;

import com.azt.front.permission.AvoidDuplicateSubmission;
import com.azt.utils.CommonUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 防止重复提交拦截器
 */
public class AvoidDuplicateSubmissionInterceptor extends HandlerInterceptorAdapter {

    private static final Logger LOGGER = Logger.getLogger(AvoidDuplicateSubmissionInterceptor.class);

    private boolean isRepeatSubmit(HttpServletRequest request) {
        String serverToken = CommonUtil.safeToString(request.getSession().getAttribute("token"));
        if(StringUtils.isBlank(serverToken)) {
            return true;
        }
        String clientToken = request.getParameter("token");
        if(StringUtils.isBlank(clientToken)) {
            return true;
        }
        return !serverToken.equals(clientToken);
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        AvoidDuplicateSubmission annotation = method.getAnnotation(AvoidDuplicateSubmission.class);
        if(annotation != null) {
            boolean needSaveSession = annotation.needSaveToken();
            if(needSaveSession) {
                request.getSession().setAttribute(annotation.name(), RandomStringUtils.random(6));
            }

            boolean needRemoveSession = annotation.needRemoveToken();
            if(needRemoveSession) {
                if(isRepeatSubmit(request)) {
                    LOGGER.warn("please don't repeat submit");
                    return false;
                }
                request.getSession().removeAttribute(annotation.name());
            }
        }
        return true;
    }
}
